package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	v1 "RoccBlog/repository/v1"
	"RoccBlog/service"
	"RoccBlog/util/generator"
	"archive/zip"
	"bytes"
	"github.com/gin-gonic/gin"
)

type GeneratorService struct {
	service.BaseService
	Repository v1.GeneratorRepository
}

func init() {
	global.RegisterService(&GeneratorService{
		Repository: v1.GeneratorRepository{},
	})
}

func (s *GeneratorService) Add(ctx *gin.Context, data model.GeneratorTable) error {
	return s.Repository.Create(data)
}

func (s *GeneratorService) Remove(ctx *gin.Context, id int) error {
	return s.Repository.Delete(id)
}

func (s *GeneratorService) Modify(ctx *gin.Context, data model.GeneratorTable) error {
	return s.Repository.Update(data)
}

func (s *GeneratorService) FindById(ctx *gin.Context, id int) (model.GeneratorTable, error) {
	return s.Repository.SelectById(id)
}

func (s *GeneratorService) Find(ctx *gin.Context) (any, error) {
	size, num := s.GetPage(ctx)
	return s.Repository.Select(num, size)
}

func (s *GeneratorService) ModifyGeneratorColumns(ctx *gin.Context, id int, columns []model.GeneratorColumn) error {
	return s.Repository.UpdateGeneratorTableColumns(id, columns)
}

func (s *GeneratorService) Preview(id int, ctx *gin.Context) (rlt any, err error) {

	//生成模式
	genModel := ctx.Query("model")

	generatorTable, err := s.FindById(ctx, id)
	if err != nil {
		return
	}

	switch genModel {
	case "":
		//单表模式
		return generator.Sigle(generatorTable)
		break
	case "masterSub":
		//主子表模式
		break
	case "tree":
		//树模式
		break
	}

	return
}

func (s *GeneratorService) DownloadCode(ctx *gin.Context, id int) error {
	rlt, err := s.Preview(id, ctx)

	//解析出错返回
	if err != nil {
		return err
	}

	var buf bytes.Buffer
	zipW := zip.NewWriter(&buf)

	for key, val := range rlt.(gin.H) {
		create, err := zipW.Create(key)
		if err != nil {
			return err
		}
		_, err = create.Write([]byte(val.(string)))
		if err != nil {
			return err
		}
	}
	err = zipW.Close()
	if err != nil {
		return err
	}

	ctx.Header("Content-Type", "application/octet-stream")
	ctx.Header("Content-Disposition", "attachment;filename=Rocc.zip")
	ctx.Header("Content-Transfer-Encoding", "binary")
	_, err = ctx.Writer.Write(buf.Bytes())

	return err
}
